package logic

import (
	"context"
	"fmt"
	"uuser/models/cache"
	"uuser/models/mysql"
	"uuser/pkg"

	"uuser/uuserrpc/internal/svc"
	"uuser/uuserrpc/uuserrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RegisterLogic) Register(in *uuserrpc.RegisterRequest) (*uuserrpc.RegisterResponse, error) {
	// todo: add your logic here and delete this line
	var user mysql.Uuser
	mysql.DB.Debug().Where("mobile = ?", in.Mobile).Find(&user)
	if user.ID != 0 {
		return nil, fmt.Errorf("注册失败,账号已存在")
	}
	a, _ := cache.Rdb.Get(cache.Ctx, "send"+in.Mobile).Result()
	if a != in.SendCode {
		return nil, fmt.Errorf("手机短信验证码错误")
	}
	b, _ := cache.Rdb.Get(cache.Ctx, "cacptcha"+in.Account).Result()
	if b != in.CaptchaCode {
		return nil, fmt.Errorf("图像验证码错误")
	}
	user.Account = in.Account
	user.Mobile = in.Mobile
	user.Password = pkg.Md5(in.Password)
	mysql.DB.Debug().Create(&user)
	return &uuserrpc.RegisterResponse{
		UserId: int64(user.ID),
	}, nil
}
